import smtplib
import random
import string
from users.models import EmailVerifyRecord
from email.mime.text import MIMEText
from email.header import Header

def random_str(randomlength=8):
    """ 生成指定长度的随机字符串方法 """
    chars = string.ascii_letters + string.digits
    strcode = ''.join(random.sample(chars, randomlength))
    return strcode


def send_email(email, send_type):
    email_record = EmailVerifyRecord()
    code = random_str()
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()

    # 邮件服务器配置
    smtp_server = 'smtp.qq.com'  # 以QQ邮箱为例
    port = 587  # 对于TLS
    username = '601010302@qq.com'  # 发件人邮箱账号
    password = 'exhblsmkhagobbgj'  # 发件人邮箱密码

    # 创建 SMTP 对象
    server = smtplib.SMTP(smtp_server, port)
    server.starttls()  # 启动TLS加密
    server.login(username, password)  # 登录邮箱

    # 创建邮件内容
    sender = '601010302@qq.com'
    recipient = email

    if send_type == 'register':
        email_title = '欢迎注册，请激活您的账户'
        email_body = '''
        <html>
            <head></head>
            <body>
                <h3>请点击以下链接激活账号：</h3>
                <a href="http://127.0.0.1:8000/users/active/{0}">激活链接</a>
            </body>
        </html>
        '''.format(code)
        message = MIMEText(email_body, 'html', 'utf-8')

    elif send_type == 'forget':
        email_title = '找回密码链接'
        email_body = '''
        <html>
            <head></head>
            <body>
                <h3>请点击以下链接修改密码：</h3>
                <a href="http://127.0.0.1:8000/users/forget_pwd_url/{0}">找回密码</a>
            </body>
        </html>
        '''.format(code)
        message = MIMEText(email_body, 'html', 'utf-8')

    message['From'] = Header(sender)
    message['To'] = Header(recipient)
    message['Subject'] = Header(email_title)

    # 发送邮件
    try:
        server.sendmail(sender, [recipient], message.as_string())
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败：", e)
    finally:
        server.quit()  # 断开SMTP连接